<template>
  <div class="general-settings space-y-6">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-foreground mb-2 flex items-center">
        <i class="i-mdi-cog mr-3 w-6 h-6" />
        {{ t('settings.general.title') }}
      </h1>
      <p class="text-muted-foreground">{{ t('settings.general.description') }}</p>
    </div>

    <!-- 启动设置 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-rocket-launch mr-2 w-5 h-5" />
        {{ t('settings.general.autoStart') }}
      </h2>

      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.autoStart') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.autoStartDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.autoStart" />
          </label>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.startToTray') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.startToTrayDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.startToTray" />
          </label>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.closeToTray') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.closeToTrayDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.closeToTray" />
          </label>
        </div>
      </div>
    </div>

    <!-- 托盘设置 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-tray-arrow-up mr-2 w-5 h-5" />
        {{ t('settings.general.traySettings') }}
      </h2>

      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.showTrayIcon') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.showTrayIconDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.showTrayIcon" />
          </label>
        </div>
      </div>
    </div>

    <!-- 语言和地区 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-translate mr-2 w-5 h-5" />
        {{ t('settings.general.language') }}
      </h2>

      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.language') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.languageDescription') }}</p>
          </div>
          <div>
            <LanguageSelector />
          </div>
        </div>
      </div>
    </div>

    <!-- 更新设置 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-update mr-2 w-5 h-5" />
        {{ t('settings.general.autoUpdate') }}
      </h2>

      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.autoUpdate') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.autoUpdateDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.autoUpdate" />
          </label>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.notifications') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.notificationsDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.betaUpdates" />
          </label>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.soundEffects') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.soundEffectsDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.soundEffects" />
          </label>
        </div>

        <div class="pt-2">
          <SecondaryButton :left-icon="'i-mdi-refresh'" @click="checkForUpdates">
            {{ t('common.update') }}
          </SecondaryButton>
        </div>
      </div>
    </div>

    <!-- 性能设置 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-speedometer mr-2 w-5 h-5" />
        {{ t('settings.general.performanceSettings') }}
      </h2>

      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-foreground mb-2">
            {{ t('settings.general.memoryLimit') }}: {{ settings.memoryLimit }}MB
          </label>
          <input
            v-model.number="settings.memoryLimit"
            type="range"
            min="512"
            max="8192"
            step="256"
            class="w-full h-2 bg-muted rounded-lg appearance-none cursor-pointer slider" />
          <div class="flex justify-between text-xs text-muted-foreground mt-1">
            <span>512MB</span>
            <span>8GB</span>
          </div>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.general.hardwareAcceleration') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.general.hardwareAccelerationDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <SwitchInput v-model="settings.hardwareAcceleration" />
          </label>
        </div>
      </div>
    </div>

    <!-- 音效测试 -->
    <AudioTestPanel v-if="settings.soundEffects" />

    <!-- 操作按钮 -->
    <div class="flex gap-3 pt-4">
      <PrimaryButton @click="saveSettings">{{ t('common.save') }}</PrimaryButton>
      <SecondaryButton @click="resetSettings">{{ t('common.reset') }}</SecondaryButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';

import { getGeneralSettings, saveGeneralSettings } from '@/api/system/app';
import LanguageSelector from '@/components/LanguageSelector.vue';
import { useConfirm } from '@/composables/useConfirm';
import { useMessage } from '@/composables/useMessage';
import { useI18n } from '@/i18n';
import audioService from '@/services/audioService';

import AudioTestPanel from './AudioTestPanel.vue';

const inited = ref(false);

// 使用 Vue I18n 的 Composition API
const { t } = useI18n();

// 使用消息API
const $message = useMessage();
const $confirm = useConfirm();

// 设置数据，用于存储常规设置项的值
const settings = ref({
  autoStart: false, // 开机启动
  startToTray: false, // 启动到托盘
  closeToTray: true, // 关闭时最小化到托盘
  language: 'zh-CN', // 界面语言
  autoUpdate: true, // 自动检查更新
  betaUpdates: false, // 接收预发布版本
  memoryLimit: 2048, // 内存使用限制 (MB)
  hardwareAcceleration: true, // 硬件加速
  showTrayIcon: true, // 显示托盘图标
  soundEffects: true // 声音效果
});

// 检查更新函数
const checkForUpdates = () => {
  console.log('检查更新...');
  $message.info(t('settings.about.updateNotAvailable'));
};

// 保存设置函数
const saveSettings = async () => {
  console.log('=== 开始保存设置 ===');

  // 创建要发送的数据副本
  const settingsToSave = { ...settings.value };

  try {
    console.log('调用saveGeneralSettings...');
    const result = await saveGeneralSettings(settingsToSave);
    console.log('保存结果:', result);

    if (result.success) {
      $message.success(t('settings.model.saveSuccess'), {
        duration: 3000
      });
      // 播放成功音效
      audioService.playSuccess();
    } else {
      console.error('保存失败，result:', result);
      $message.error(t('settings.model.saveFailed'));
      // 播放错误音效
      audioService.playError();
    }
  } catch (error: any) {
    console.error('保存常规设置异常:', error);
    $message.error(t('settings.model.saveFailed'));
    // 播放错误音效
    audioService.playError();
  }
  console.log('=== 保存设置结束 ===');
};

// 加载设置函数
const loadSettings = async () => {
  try {
    const result = await getGeneralSettings();
    if (result && result.success && result.data) {
      // 使用默认值合并API返回的数据
      const defaultSettings = {
        autoStart: false,
        startToTray: false,
        closeToTray: true,
        language: 'zh-CN',
        autoUpdate: true,
        betaUpdates: false,
        memoryLimit: 2048,
        hardwareAcceleration: true,
        showTrayIcon: true,
        soundEffects: true
      };
      settings.value = Object.assign(defaultSettings, result.data);

      // 同步音效服务状态
      audioService.setEnabled(settings.value.soundEffects);

      console.log('已加载常规设置:', settings.value);
    } else {
      console.error('获取常规设置失败:', result);
      $message.warning(t('settings.model.connectionFailed'));
    }
  } catch (error: any) {
    console.error('加载常规设置失败:', error);
    $message.error(t('settings.model.connectionFailed'));
  }
};

// 组件挂载时加载设置
onMounted(async () => {
  if (!inited.value) {
    await loadSettings();
    inited.value = true;
  }
});

// 重置设置函数，将所有设置恢复到默认值
const resetSettings = async () => {
  try {
    const confirmed = await $confirm.warning(t('settings.appearance.resetConfirm'), {
      title: t('common.reset'),
      confirmText: t('common.reset'),
      cancelText: t('common.cancel')
    });

    if (confirmed) {
      settings.value = {
        autoStart: false,
        startToTray: false,
        closeToTray: true,
        language: 'zh-CN',
        autoUpdate: true,
        betaUpdates: false,
        memoryLimit: 2048,
        hardwareAcceleration: true,
        showTrayIcon: true,
        soundEffects: true
      };
      console.log('常规设置已重置');
      $message.info(t('settings.appearance.resetSuccess'));
      // 播放通知音效
      audioService.playNotification();
    }
  } catch {
    // 用户取消了操作
    console.log('用户取消了重置操作');
  }
};

// 监听托盘图标显示设置的变化，提供即时反馈
watch(
  () => settings.value.showTrayIcon,
  (newValue, oldValue) => {
    if (!inited.value || newValue === oldValue) {
      return;
    }

    console.log('托盘图标显示设置变化:', { from: oldValue, to: newValue });

    if (newValue) {
      $message.success('托盘图标已显示');
    } else {
      $message.info('托盘图标已隐藏');
      // 如果托盘被禁用，提醒用户关闭行为的变化
      if (settings.value.closeToTray) {
        $message.warning('注意：托盘已隐藏，关闭窗口将退出应用', {
          duration: 5000
        });
      }
    }
  }
);

// 监听音效设置的变化，同步音效服务状态
watch(
  () => settings.value.soundEffects,
  (newValue, oldValue) => {
    if (!inited.value || newValue === oldValue) {
      return;
    }

    console.log('音效设置变化:', { from: oldValue, to: newValue });

    // 同步音效服务状态
    audioService.setEnabled(newValue);

    if (newValue) {
      $message.success('音效已启用');
      // 播放一个测试音效
      audioService.playStartup();
    } else {
      $message.info('音效已禁用');
    }
  }
);

watch(
  settings,
  (newVal) => {
    if (!inited.value) {
      return;
    }
    console.log('=== Settings Changed ===');
    console.log('New settings:', newVal);
    saveSettings();
    console.log('========================');
  },
  { deep: true }
);
</script>

<style lang="scss" scoped></style>
